import React, {Component} from 'react'
import {connect} from 'react-redux'
import { Toast} from 'antd-mobile';
import { Link } from "react-router-dom";

import Header from "../components/header";
import OrderItemBase from "../components/orderitemstyle/orderItemBase"
import OrderItemLM from "../components/orderitemstyle/orderItemLM"
import OrderItemGG from "../components/orderitemstyle/orderItemGG"
import OrderItemGroup from "../components/orderitemstyle/orderItemGroup"
import OrderItemDW from "../components/orderitemstyle/orderItemDw"
import BetTimerNoRefresh from "../components/betTimerNoRefresh"

import {parseQuery} from "../utils/tools"
import {loadPankKouList,loadPeilvData,getGameInfo,tempSaveSelectedPeiyu,getLmOrder,saveOrder,removeAllselect} from "../redux/actions/betcenterAction"
import {loadUserInfo} from "../redux/actions/userAction"
import {RES_OK_CODE} from "../redux/types/index"

class OrderMoneyContainer extends Component {
  constructor (props){
   super(props)
   this.submitProcess = false;
   this.state= {
    fenpanSecond:0,
    kaijiangSecond:0,
    fenpanZhong: false,
    kaijiangZhong: false
   };
   this.initDataTimeout = null
   
}
componentWillMount(){
    const {dispatch, location, betcenter, history} = this.props;
    let query = parseQuery(location.search);
    let selectedPeiyu = betcenter.get("selectPeiyu")
    let num = Object.keys(selectedPeiyu).length
    if (Object.keys(selectedPeiyu).length <= 0 ) {
      let to = `/betcenter/${query.gameCode}`;
      history.push(to);
    } else {
      if(query.gameCode=="BJKL8"){
        return dispatch(getGameInfo(query.gameCode, "TM")); 
      }
      dispatch(loadUserInfo())
      dispatch(getGameInfo(query.gameCode, query.pankou)); 
    }
    // const {name,money} = betcenter.get("selectnamemoney")
  }
renderBetForm(){
    const {betcenter,location} = this.props;
    const {name,money} = betcenter.get("selectnamemoney")
    let order = betcenter.get("selectPeiyu")
    // let order = {"EZDW-EZDW-EZDW" : {number: "万:0|仟:1", maxLimit: 20000, minLimit: 1, id: "EZDW-EZDW-EZDW", pl: 83} }
    // console.log(order);
    let {gameCode,pankou} =  parseQuery(location.search)
    var platformInfo = betcenter.get("gameinfo")
    // var platformInfo = {"datas":{"lastQs":"20180328-052","lastResult":"0,4,3,4,3","currentQs":"20180328-053","nowtime":1522219301,"closetime":1522219740,"animal":{"SHU":["11","23","35","47"],"TU":["08","20","32","44"],"SHE":["06","18","30","42"],"MA":["05","17","29","41"],"ZHU":["12","24","36","48"],"YANG":["04","16","28","40"],"NIU":["10","22","34","46"],"GOU":["01","13","25","37","49"],"HU":["09","21","33","45"],"LONG":["07","19","31","43"],"HOU":["03","15","27","39"],"JI":["02","14","26","38"]},"opentime":1522219800,"betInfo":{"maxLimit":{"EZHS":50000,"DXDS":50000,"EZZH":50000,"ZXS":50000,"YZZH":50000,"SZP":50000,"EZDW":50000,"KD":50000,"LH":50000,"YZDW":50000,"SZDW":50000,"ZXL":50000},"odds":{"EZDW-EZDW-EZDW":83},"oddinfo":[{"EZDW":"二字定位"},{"EZDW":"二字定位"},{"EZDW":"二字定位"}],"minLimit":{"EZHS":1,"DXDS":1,"EZZH":1,"ZXS":1,"YZZH":1,"SZP":1,"EZDW":1,"KD":1,"LH":1,"YZDW":1,"SZDW":1,"ZXL":1},"maxPeriodLimit":{"EZHS":200000,"DXDS":200000,"EZZH":200000,"ZXS":200000,"YZZH":200000,"SZP":200000,"EZDW":200000,"KD":200000,"LH":200000,"YZDW":200000,"SZDW":200000,"ZXL":200000}},"status":0},"errorCode":"000000","msg":"操作成功"}.datas
    //   console.info(order," da");
    // console.log(gameCode,pankou,"ff");
  if(pankou == "LM" && gameCode == "HK6"){
    return <OrderItemLM {...this.props} items={order} onSubmit={this.onBetSubmit.bind(this)}  platform={platformInfo} baseinfo={{name,money}}></OrderItemLM>
  }

  if(pankou == "GG"){
    return <OrderItemGG {...this.props} items={order} onSubmit={this.onBetSubmit.bind(this)}  platform={platformInfo} baseinfo={{name,money}}></OrderItemGG> 
  } 

  if(pankou == "ZYBZ" || pankou =="LX" || pankou =="HX" || pankou =="ZXL" || pankou =="ZXS" || pankou =="WSL" || (pankou == "LM" && gameCode == "GDKLSF")){
    return <OrderItemGroup {...this.props} items={order} onSubmit={this.onBetSubmit.bind(this)}  platform={platformInfo} baseinfo={{name,money}} ></OrderItemGroup>
  }

  if(pankou == 'DW' || pankou == 'EZDW' || pankou == 'SZDW' || pankou == 'EZZH'){
   return <OrderItemDW {...this.props} items={order} onSubmit={this.onBetSubmit.bind(this)}  platform={platformInfo} baseinfo={{name,money}} ></OrderItemDW>
  } 
  return <OrderItemBase {...this.props} items={order} onSubmit={this.onBetSubmit.bind(this)}  platform={platformInfo} baseinfo={{name,money}}></OrderItemBase>
}
removeAll(){
  const {dispatch} = this.props
  dispatch(removeAllselect())
  // 清空
}
onBetSubmit(betItems, orderFlag = 'normal') {
    if (this.submitProcess) {
      return false;
    }
    if(betItems.length==0){
     return Toast.fail('请选择下注内容',2);
    }
    this.submitProcess = true;
    let _this = this;
    const {dispatch, history,location} = this.props;
    let {gameCode,pankou} = parseQuery(location.search)
    Toast.loading("下注中",0)
    dispatch(saveOrder(gameCode, betItems, (data) => {
      _this.submitProcess = false;
      if (data.errorCode == RES_OK_CODE) {
        Toast.success('订单下注成功',2);
        dispatch(removeAllselect())
        let to = `/betcenter/${gameCode}/`;
        history.push(to);
      } else {
        Toast.fail(data.msg,2);
      }
    }, orderFlag));
    
  }
  componentWillReceiveProps(nextProps){
    this.setTime(nextProps)
  }
  setTime(nextProps){
    const gameinfo = nextProps.betcenter.get("gameinfo")
    const {location} = nextProps;
    let {gameCode} = parseQuery(location.search)

    if (gameinfo) {
      let fenpanSecond = gameinfo.closetime - gameinfo.nowtime;
      let kaijiangSecond = gameinfo.opentime - gameinfo.nowtime;

      this.setState({
        fenpanSecond,
        kaijiangSecond
      });

      // 封盘结束
      if (fenpanSecond > 0) {
        this.setState({
          fenpanZhong: false,
          kaijiangZhong: false
        });
      }
        
      // 开奖结束
      if (fenpanSecond > 0 && kaijiangSecond > 0 ) {
        this.setState({
          kaijiangZhong: false
        });
      }

      // 封盘中
      if (fenpanSecond < 0 && kaijiangSecond > 0) {
        this.setState({
          kaijiangZhong: false,
          fenpanZhong: true,
        });
        this.props.history.replace("/betcenter/"+gameCode)
      }
    
      // 开奖中
      if (fenpanSecond < 0 && kaijiangSecond < 0) {
        this.setState({
          kaijiangZhong: true,
          fenpanZhong: false,
        });
        this.props.history.replace("/betcenter/"+gameCode)
      }

      if ( gameinfo.closetime 
        && gameinfo.nowtime 
        && kaijiangSecond < 0 ) {

        this.setState({
          kaijiangZhong: true
        });
        
        let _this = this;
        if (this.initDataTimeout) {
          clearTimeout(this.initDataTimeout);
        }
        this.initDataTimeout = setTimeout( () => {
          _this.initDataTimeout = null;
          _this.loadCaiPiaoData();
        },  Math.abs(kaijiangSecond*1000) );
      } else {
        //
      }
    }
    
  }
  onFenpanFinish() {
    let kaijiangSecond = this.state.kaijiangSecond - this.state.fenpanSecond;
    this.setState({
      fenpanZhong: true,
      fenpanSecond: 0,
      kaijiangSecond: kaijiangSecond
    });
    const {location} = this.props;
    let {gameCode} = parseQuery(location.search)
    Toast.success('已封盘，请重新下注',2);
    let to = `/betcenter/${gameCode}/`;
    this.props.history.replace("/betcenter/"+gameCode)
  }
  onKaijiangFinish() {
    console.log('开奖完成...')
    this.setState({
      fenpanZhong: false,
      kaijiangZhong: true,
      fenpanSecond: 0,
      kaijiangSecond: 0
    });
  }
  render() {
    const {betcenter,location,user} = this.props;
    const {fenpanSecond,kaijiangSecond,fenpanZhong,kaijiangZhong} = this.state
    let {gameCode} = parseQuery(location.search)
    let order = betcenter.get("selectPeiyu")
    const gameinfo=betcenter.get("gameinfo")
   return <div className="order">
         <Header title="投注清单" {...this.props}></Header>
         <div className="timestop">
              {/* <h3>200202期 2909-2-2 </h3> */}
              <BetTimerNoRefresh 
              currentQs={gameinfo.currentQs}
              fpSecond={ fenpanSecond}
              kjSecond={ kaijiangSecond }
              kaijiang={this.onKaijiangFinish.bind(this)}
              fenpan={this.onFenpanFinish.bind(this)}
              ></BetTimerNoRefresh>
              {/* <ul>
                <li><Link to={"/betcenter/"+gameCode}>再选一注</Link></li>
                <li>机选一注</li>
                <li onClick={this.removeAll.bind(this)}>全部清空</li>
              </ul> */}
              <div className="userinfo">
                <p>会员账号：<span className="red">{user.get('auth').get("userName")}</span>  余额：<span className="red">{user.get('info').userMoney}</span></p>
              </div>
         </div>
         <div className="container">
            <div className="orderitems">
                  {this.renderBetForm()}
            </div>
            </div>
   </div>
   }
}

function mapStateToProps(state) {
  return {
    betcenter: state.betcenter,
    user:state.user
  }
}

export default connect(mapStateToProps)(OrderMoneyContainer)